import echarts from '@/ntils/echart'
import type { EChartsOption } from 'echarts'
import { unref, nextTick, watch, computed, ref } from 'vue'
import type { Ref } from 'vue'
import { echartTheme } from '@/styles/echartConfig';
let Instance = ref()
export function useECharts(
    elRef: Ref<HTMLDivElement>,
    theme: 'light' | 'dark' | 'default', 
) {
    let chartInstance: echarts.ECharts | null = null
    const cacheOptions = ref({}) 
    const el = unref(elRef)
    const t = theme
    if(t!=='default' && t!=='light'){
        echarts.registerTheme(t,echartTheme)
    }
    // 图表配置 响应式 cacheOptions
    const getOptions = computed(() => {
        if (theme !== 'dark') {
            return cacheOptions.value as EChartsOption
        }
        return {
            backgroundColor: 'transparent',
            ...cacheOptions.value,
        } as EChartsOption
    })
    
    function setOptions(options:EChartsOption, clear = true) {
        cacheOptions.value = options
        nextTick(() => {
            // 初始化 t 为主题 有黑暗主题
            chartInstance = echarts.init(el, t)  
            // 清除之前的动画 为下次更新做准备
            clear && chartInstance?.clear()
            // 更新数据  
            chartInstance?.setOption(unref(getOptions))
            resizeFn(chartInstance)
            Instance.value = chartInstance
        })
    }
    // 获取实例
    function getInstance(): echarts.ECharts | null {
        return chartInstance
    }
    // 自适应宽度
    function resizeFn(chartInstance) {
        window.addEventListener('resize', () => {
            chartInstance?.resize()
        }) 
    }
    // 监听主题变化
    watch(
        () => theme,
        () => {
            if (chartInstance) {
                chartInstance.dispose()
                setOptions(cacheOptions.value)
            }
        },
    ) 
    
    return {
        setOptions,
        echarts,
        chartInstance,
        getInstance,
    }  
}